package alarmdisplay;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import java.awt.*;
import javax.swing.*;

public class Kartendienst {
	private static String strURL1 = "";
	private static String strURL2 = "";
	private static String strURL3 = "";
	private static ImageIcon imageIcon = new ImageIcon();
	private static Vector<String> routenList = new Vector<String>();

	public Kartendienst(Frame frame) {

	}

	public static String kartenDienst(String sStrasse, String sPLZ,
			String sOrt, String sArt, JLabel jIconLabel, Frame frame, String sLat, String sLon) {
		Debug.debug("KARTENDIENST", "DEBUG>> Kartendienst V1.10");

		sStrasse = sStrasse.replace("Ä", "%C3%84");
		sStrasse = sStrasse.replace("Ö", "%C3%96");
		sStrasse = sStrasse.replace("Ü", "%C3%9C");
		sStrasse = sStrasse.replace("ä", "%C3%A4");
		sStrasse = sStrasse.replace("ö", "%C3%B6");
		sStrasse = sStrasse.replace("ü", "%C3%BC");
		sStrasse = sStrasse.replace("ß", "%C3%9F");
		sStrasse = sStrasse.replace(" ", "+");
		Debug.debug("KARTENDIENST", "DEBUG>> Strasse: " + sStrasse);
		Debug.debug("KARTENDIENST", "DEBUG>>     PLZ: " + sPLZ);
		Debug.debug("KARTENDIENST", "DEBUG>>     Ort: " + sOrt);

		if (sArt.equals("1")) {
			return kartenDienst1(sStrasse, sPLZ, sOrt, jIconLabel);
		} else if (sArt.equals("2")) {
			return kartenDienst2(sStrasse, sPLZ, sOrt, jIconLabel);
		} else if (sArt.equals("3")) {
			return kartenDienst3(sStrasse, sPLZ, sOrt, jIconLabel);
		} else if (sArt.equals("4")) {
			return kartenDienst4(sStrasse, sPLZ, sOrt, jIconLabel, frame, sLat, sLon);
		} else if (sArt.equals("5")) {
			return kartenDienst5(sStrasse, sPLZ, sOrt, jIconLabel, frame);
		}
		return "";
	}

	/**
	 * Kartendienst (Google) ansprechen
	 */
	private static String kartenDienst1(String sStrasse, String sPLZ,
			String sOrt, JLabel jIconLabel) {
		try {
			strURL1 = "http://maps.googleapis.com/maps/api/staticmap?zoom=14&size=640x640"
					+ "&maptype=roadmap&markers=color:green%7Clabel:S%7CT%C3%B6nnh%C3%A4user+Weg+69,+21423+,+Germany&"
					+ "markers=color:red%7Clabel:E%7C"
					+ sStrasse
					+ ",+"
					+ sPLZ
					+ "+" + sOrt + "&sensor=false";
			strURL2 = "http://maps.googleapis.com/maps/api/staticmap?zoom=16&size=640x640"
					+ "&maptype=roadmap&markers=color:red%7Clabel:E%7C"
					+ sStrasse + ",+" + sPLZ + "+" + sOrt + "&sensor=false";
			strURL3 = "http://maps.googleapis.com/maps/api/directions/xml?origin=T%C3%B6nnh%C3%A4user+Weg+69,+21423+,+Germany&destination="
					+ sStrasse
					+ ",+"
					+ sPLZ
					+ "+"
					+ sOrt
					+ ",+Germany&sensor=false&language=de";
			Debug.debug("KARTENDIENST1", "DEBUG>>     URL:  " + strURL1);
			Debug.debug("KARTENDIENST1", "DEBUG>>     URL2: " + strURL2);
			Debug.debug("KARTENDIENST1", "DEBUG>>     URL3: " + strURL3);

			imageIcon = new ImageIcon(new URL(strURL1));
		} catch (MalformedURLException e) {
			Debug.debug("KARTENDIENST1", "ERROR>> " + e);
		}
		jIconLabel.setIcon(imageIcon);
		return strURL1;
	}

	/**
	 * Kartendienst (Anderer) ansprechen
	 */
	private static String kartenDienst2(String sStrasse, String sPLZ,
			String sOrt, JLabel jIconLabel) {
		JFrame jf = new JFrame();
		JLabel j1 = new JLabel();
		ImageIcon icon = new ImageIcon();
		String sLat = "", sLon = "";
		String result = "";
		try {
			URL url = new URL("http://nominatim.openstreetmap.org/search?q="
					+ sStrasse + "," + sPLZ + "+" + sOrt
					+ "&format=xml&polygon=1&addressdetails=1");
			URLConnection connection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				if (line.indexOf("lat=") != -1) {
					sLat = line.substring(line.indexOf("lat="), line.length());
					sLat = sLat.substring(0, sLat.indexOf(" "));
					sLat = sLat.substring(5, sLat.length() - 1);
					Debug.debug("KARTENDIENST2", "DEBUG>> Karte2-lat! "
							+ sLat);
				}
				if (line.indexOf("lon=") != -1) {
					sLon = line.substring(line.indexOf("lon="), line.length());
					sLon = sLon.substring(0, sLon.indexOf(" "));
					sLon = sLon.substring(5, sLon.length() - 1);
					Debug.debug("KARTENDIENST2", "DEBUG>> Karte2-lon! "
							+ sLon);
				}

				result = result + line;
			}
		} catch (IOException exception) {
			Debug.debug("KARTENDIENS2T", "Fehler: " + exception);
		}
		jf.setTitle("Testfenster...!!!");
		jf.setSize(1024, 768);
		jf.getContentPane().setLayout(new BorderLayout());
		jf.getContentPane().add(j1, BorderLayout.CENTER);
		try {
			icon = new ImageIcon(new URL(
					"http://staticmap.openstreetmap.de/staticmap.php?center="
							+ sLat + "," + sLon
							+ "&zoom=17&size=1024x1024&markers=" + sLat + ","
							+ sLon + ",red-pushpin"));
		} catch (MalformedURLException e) {
			Debug.debug("KARTENDIENST2", "ERROR>> " + e);
		}

		j1.setIcon(icon);
		jf.setVisible(true);
		return strURL1;
	}

	/**
	 * Kartendienst3 (OSM) ansprechen
	 */
	private static String kartenDienst3(String sStrasse, String sPLZ,
			String sOrt, JLabel jIconLabel) {
		String sLat = "", sLon = "";
		try {
			String result = "";
			URL url = new URL("http://nominatim.openstreetmap.org/search?q="
					+ sStrasse + "," + sPLZ + "+" + sOrt
					+ "&format=xml&polygon=1&addressdetails=1");
			URLConnection connection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			boolean bFoundHighway = false;
			while ((line = in.readLine()) != null) {
				if (line.indexOf("highway") != -1) {
					bFoundHighway = true;
				}
				if (bFoundHighway) {
					if (line.indexOf("lat=") != -1) {
						sLat = line.substring(line.indexOf("lat="),
								line.length());
						sLat = sLat.substring(0, sLat.indexOf(" "));
						sLat = sLat.substring(5, sLat.length() - 1);
						Debug.debug("KARTENDIENST3",
								"DEBUG>> Karte2-lat! " + sLat);
					}
					if (line.indexOf("lon=") != -1) {
						sLon = line.substring(line.indexOf("lon="),
								line.length());
						sLon = sLon.substring(0, sLon.indexOf(" "));
						sLon = sLon.substring(5, sLon.length() - 1);
						Debug.debug("KARTENDIENST3",
								"DEBUG>> Karte2-lon! " + sLon);
					}
					break;
				}
				result = result + line;
			}
		} catch (IOException exception) {
			Debug.debug("KARTENDIENST3", "Fehler: " + exception);
		}
		try {
			imageIcon = new ImageIcon(new URL(
					"http://staticmap.openstreetmap.de/staticmap.php?center="
							+ sLat + "," + sLon
							+ "&zoom=17&size=800x600&markers=" + sLat + ","
							+ sLon + ",red-pushpin"));
			Debug.debug(
					"KARTENDIENST3",
					"DEBUG>>>" + imageIcon.getIconHeight() + "x"
							+ imageIcon.getIconWidth());
		} catch (MalformedURLException e) {
			Debug.debug("KARTENDIENST3", "ERROR>> " + e);
		}
		System.out
				.println("DEBUG>> http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=json&routeType=shortest&timeType=1&enhancedNarrative=false&shapeFormat=raw&generalize=200&locale=de_DE&unit=k&from=53.3653795,10.2096754&to="
						+ sLat
						+ ","
						+ sLon
						+ "&drivingStyle=2&highwayEfficiency=21.0");
		jIconLabel.setIcon(imageIcon);
		return strURL1;
	}

	/**
	 * Kartendienst4 (Geocoding: Google/Karte: OSM)
	 */
	private static String kartenDienst4(String sStrasse, String sPLZ,
			String sOrt, JLabel jIconLabel, Frame frame, String sLat, String sLon) {
		//String sLat = "", sLon = "";
		
		try {
			if (sLat.equals("")) {
				Debug.debug("KARTENDIENST4", "DEBUG>>> Koordinaten ziehen" + sLat + " - " + sLon);
				String result = "";
				// URL url = new URL("http://maps.google.com/maps/geo?q=" + sStrasse
				// + "," + sPLZ + "+" + sOrt + "&output=xml&sensor=false");
				URL url = new URL(
						"http://maps.googleapis.com/maps/api/geocode/xml?address="
								+ sStrasse + "," + sPLZ + "+" + sOrt
								+ "&sensor=false");
				URLConnection connection = url.openConnection();
				Debug.debug("KARTENDIENST4", "DEBUG>>>" + url);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				String line;
	
				boolean bFlag = false;
				while ((line = in.readLine()) != null) {
					Debug.debug("KARTENDIENST4", "DEBUG>> " + line);
					if (line.indexOf("<location>") != -1) {
						Debug.debug("KARTENDIENST4", "DEBUG>> Flag found");
						bFlag = true;
					}
					if (bFlag == true) {
						if (line.indexOf("<lat>") != -1) {
							sLat = line.substring(line.indexOf("<lat>"),
									line.length());
							Debug.debug("KARTENDIENST4",
									"DEBUG>> Karte1a-lat! " + sLat);
							sLat = sLat.substring(0, sLat.indexOf("</lat>"));
							Debug.debug("KARTENDIENST4",
									"DEBUG>> Karte1b-lat! " + sLat);
							sLat = sLat.substring(5, sLat.length() - 1);
							Debug.debug("KARTENDIENST4",
									"DEBUG>> Karte1c-lat! " + sLat);
						}
						if (line.indexOf("<lng>") != -1) {
							sLon = line.substring(line.indexOf("<lng>"),
									line.length());
							sLon = sLon.substring(0, sLon.indexOf("</lng>"));
							sLon = sLon.substring(5, sLon.length() - 1);
							Debug.debug("KARTENDIENST4",
									"DEBUG>> Karte1-lng! " + sLon);
							break;
						}
					}
				}
					
				/*
				 * while ((line = in.readLine()) != null) {
				 * Debug.debug("KARTENDIENST4", "DEBUG>> " + line); if
				 * (line.indexOf("<location>") != -1) { StringTokenizer sc = new
				 * StringTokenizer(line.substring(24), ","); sLon =
				 * sc.nextToken().trim(); //sLon sLat = sc.nextToken().trim();
				 * //sLat Debug.debug("KARTENDIENST4", "DEBUG>> " + sLat + ","
				 * + sLon); break; } result = result + line; }
				 */
				// Image in Anzeige
				if (bFlag == false) {
					Debug.debug("KARTENDIENST4", "DEBUG>> Dummy Bild einfuegen");
					imageIcon = new ImageIcon("test.gif");
					jIconLabel.setIcon(imageIcon);
					return "";				
				}
			}			
			
			strURL1 = "http://staticmap.openstreetmap.de/staticmap.php?center="
					+ sLat + "," + sLon + "&zoom=17&size=900x1200&markers="
					+ sLat + "," + sLon + ",red-pushpin";
			// TODO
			// strURL1="http://staticmap.openstreetmap.de/staticmap.php?center="
			// + sLat + "," + sLon + "&zoom=17&size="+(frame.getBounds().width -
			// 390)+"x"+(frame.getBounds().height - 380)+"&markers=" + sLat +
			// "," + sLon + ",red-pushpin";

			Debug.debug("KARTENDIENST4", "DEBUG>>" + strURL1);
			imageIcon = new ImageIcon(new URL(strURL1));

			Debug.debug(
					"KARTENDIENST4",
					"DEBUG>>" + imageIcon.getIconHeight() + "x"
							+ imageIcon.getIconWidth());

			// Koordinaten für Routenberechnung
			URL url = new URL("http://nominatim.openstreetmap.org/search?q="
					+ sStrasse + "," + sPLZ + "+" + sOrt
					+ "&format=xml&polygon=1&addressdetails=1");
			URLConnection connection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				if (line.indexOf("lat=") != -1) {
					sLat = line.substring(line.indexOf("lat="), line.length());
					sLat = sLat.substring(0, sLat.indexOf(" "));
					sLat = sLat.substring(5, sLat.length() - 1);
					Debug.debug("KARTENDIENST4", "DEBUG>> Karte2-lat! "
							+ sLat);
				}
				if (line.indexOf("lon=") != -1) {
					sLon = line.substring(line.indexOf("lon="), line.length());
					sLon = sLon.substring(0, sLon.indexOf(" "));
					sLon = sLon.substring(5, sLon.length() - 1);
					Debug.debug("KARTENDIENST4", "DEBUG>> Karte2-lon! "
							+ sLon);
				}
				String result = "";
				result = result + line;
			}
/*
			// Route berechnen
			url = new URL(
					"http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=json&routeType=shortest&timeType=1&enhancedNarrative=false&shapeFormat=raw&generalize=200&locale=de_DE&unit=k&from=53.3689900,10.2190500&to="
							+ sLat
							+ ","
							+ sLon
							+ "&drivingStyle=2&highwayEfficiency=21.0");
			connection = url.openConnection();
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String RouteJSON;
			RouteJSON = in.readLine();
			Debug.debug("KARTENDIENST4", "DEBUG>> " + RouteJSON);
			List<String> route = new JSON2txt().getStringsFromField(RouteJSON);
			for (String eachroute : route) {
				routenList.add(eachroute);
				Debug.debug("KARTENDIENST4", "DEBUG>> " + eachroute);
			}
			Debug.debug("KARTENDIENST4", "DEBUG>> " + url);
*/                        
			jIconLabel.setIcon(imageIcon);
		} catch (Exception exception) {
			Debug.debug("KARTENDIENST4", "ERROR>> " + exception);
		}
		return strURL1;
	}

	/**
	 * Kartendienst5 (Geocoding: Google/Karte: OSM)
	 */
	private static String kartenDienst5(String sStrasse, String sPLZ,
			String sOrt, JLabel jIconLabel, Frame frame) {
		String sLat = "", sLon = "";
		try {
			String result = "";
			URL url = new URL("http://nominatim.openstreetmap.org/search?q="
					+ sStrasse + "," + sPLZ + "+" + sOrt
					+ "&format=xml&polygon=1&addressdetails=1");
			Debug.debug("KARTENDIENST5", "DEBUG>>>" + url);
			URLConnection connection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			boolean bFoundHighway = false;
			while ((line = in.readLine()) != null) {
				if (line.indexOf("highway") != -1) {
					bFoundHighway = true;
				}
				if (bFoundHighway) {
					if (line.indexOf("lat=") != -1) {
						sLat = line.substring(line.indexOf("lat="),
								line.length());
						sLat = sLat.substring(0, sLat.indexOf(" "));
						sLat = sLat.substring(5, sLat.length() - 1);
						Debug.debug("KARTENDIENST5",
								"DEBUG>> Karte2-lat! " + sLat);
					}
					if (line.indexOf("lon=") != -1) {
						sLon = line.substring(line.indexOf("lon="),
								line.length());
						sLon = sLon.substring(0, sLon.indexOf(" "));
						sLon = sLon.substring(5, sLon.length() - 1);
						Debug.debug("KARTENDIENST5",
								"DEBUG>> Karte2-lon! " + sLon);
					}
					break;
				}
				result = result + line;
			}
			strURL1 = "http://staticmap.openstreetmap.de/staticmap.php?center="
					+ sLat + "," + sLon + "&zoom=16&size="
					+ (frame.getBounds().width - 390) + "x"
					+ (frame.getBounds().height - 380) + "&markers=" + sLat
					+ "," + sLon + ",red-pushpin";
			Debug.debug("KARTENDIENST5", "DEBUG>>>" + strURL1);

			imageIcon = new ImageIcon(new URL(strURL1));

			Debug.debug(
					"KARTENDIENST5",
					"DEBUG>>>" + imageIcon.getIconHeight() + "x"
							+ imageIcon.getIconWidth());

			// Koordinaten für Routenberechnung
			// url = new URL("http://nominatim.openstreetmap.org/search?q=" +
			// sStrasse + "," + sPLZ + "+" + sOrt +
			// "&format=xml&polygon=1&addressdetails=1");
			// connection = url.openConnection();
			// in = new BufferedReader(new
			// InputStreamReader(connection.getInputStream()));
			// while ((line = in.readLine()) != null) {
			// if (line.indexOf("lat=") != -1) {
			// sLat = line.substring(line.indexOf("lat="), line.length());
			// sLat = sLat.substring(0, sLat.indexOf(" "));
			// sLat = sLat.substring(5, sLat.length()-1);
			// Debug.debug("KARTENDIENST", "DEBUG>> Karte2-lat! " + sLat);
			// }
			// if (line.indexOf("lon=") != -1) {
			// sLon = line.substring(line.indexOf("lon="), line.length());
			// sLon = sLon.substring(0, sLon.indexOf(" "));
			// sLon = sLon.substring(5, sLon.length()-1);
			// Debug.debug("KARTENDIENST", "DEBUG>> Karte2-lon! " + sLon);
			// }
			//
			// result = result + line;
			// }

			// Route berechnen
			url = new URL(
					"http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=json&routeType=shortest&timeType=1&enhancedNarrative=false&shapeFormat=raw&generalize=200&locale=de_DE&unit=k&from=53.3689900,10.2190500&to="
							+ sLat
							+ ","
							+ sLon
							+ "&drivingStyle=2&highwayEfficiency=21.0");
			connection = url.openConnection();
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String RouteJSON;
			RouteJSON = in.readLine();
			Debug.debug("KARTENDIENST5", "DEBUG>> " + RouteJSON);
			List<String> route = new JSON2txt().getStringsFromField(RouteJSON);
			for (String eachroute : route) {
				Debug.debug("KARTENDIENST5", "DEBUG>> " + eachroute);
			}
			Debug.debug("KARTENDIENST5", "DEBUG>> " + url);
			jIconLabel.setIcon(imageIcon);
		} catch (Exception exception) {
			Debug.debug("KARTENDIENST5", "ERROR>> " + exception);
		}
		return strURL1;
	}

	/**
	 * Lesen aus der URL und Rückgabe eines Stringarrays mit Wegbeschreibung
	 */
	public static Vector<String> getFormatierterWeg() {
		Vector returnVector = new Vector<String>();
		String km;
		String way;
		String[] split;
		//TODO
		for (String eachRoute : routenList) {
			split=eachRoute.split("#");
			km=split[1];
			way=split[0];
			
			
		}

		return returnVector;
	}
}
